package com.yyydjk.library.activitys;

import android.Manifest;
import android.animation.Animator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.GetCallback;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.mikepenz.foundation_icons_typeface_library.FoundationIcons;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic;
import com.squareup.picasso.Picasso;
import com.yyydjk.library.R;
import com.yyydjk.library.base.BaseActivity;
import com.yyydjk.library.event.SkinChangeEvent;
import com.yyydjk.library.fragments.AndroidLibraryFragment;
import com.yyydjk.library.fragments.JiaoChengFragment;
import com.yyydjk.library.theme.ColorRelativeLayout;
import com.yyydjk.library.theme.ColorUiUtil;
import com.yyydjk.library.theme.ColorView;
import com.yyydjk.library.theme.Theme;
import com.yyydjk.library.utils.AppVersionUtils;
import com.yyydjk.library.utils.PreUtils;
import com.yyydjk.library.utils.SystemUtils;
import com.yyydjk.library.utils.ThemeUtils;
import com.yyydjk.library.value.AppValue;
import com.yyydjk.library.value.NetValue;
import com.yyydjk.library.widget.ResideLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;
import me.xiaopan.android.content.res.DimenUtils;
import me.xiaopan.android.preference.PreferencesUtils;
import me.xiaopan.android.widget.ToastUtils;

public class MainActivity extends BaseActivity implements ColorChooserDialog.ColorCallback {
    @Bind(R.id.avatar) ImageView mAvatar;
    @Bind(R.id.desc) TextView mDesc;
    @Bind(R.id.android) TextView mAndroid;
    @Bind(R.id.update) TextView mUpdate;
    @Bind(R.id.jiaocheng) TextView mJiaocheng;
    @Bind(R.id.front) TextView mFront;
    @Bind(R.id.app) TextView mApp;
    @Bind(R.id.scrollView) ScrollView mScrollView;
    @Bind(R.id.about) TextView mAbout;
    @Bind(R.id.theme) TextView mTheme;
    @Bind(R.id.menu) ColorRelativeLayout mMenu;
    @Bind(R.id.status_bar) ColorView mStatusBar;
    @Bind(R.id.icon) ImageView mIcon;
    @Bind(R.id.title) TextView mTitle;
    @Bind(R.id.container) FrameLayout mContainer;
    @Bind(R.id.resideLayout) ResideLayout mResideLayout;
    private boolean updateFlag=false;
    private FragmentManager fragmentManager;
    private String currentFragmentTag;
    private int appVersionCode;
    private boolean isShouDongUpdate=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        appVersionCode = AppVersionUtils.getVersionCode(this);
        chechPremission();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mStatusBar.setVisibility(View.VISIBLE);
            mStatusBar.getLayoutParams().height = SystemUtils.getStatusHeight(this);
            mStatusBar.setLayoutParams(mStatusBar.getLayoutParams());
        } else {
            mStatusBar.setVisibility(View.GONE);
        }

        setIconDrawable(mAndroid, MaterialDesignIconic.Icon.gmi_android);
        setIconDrawable(mFront, MaterialDesignIconic.Icon.gmi_language_javascript);
        setIconDrawable(mApp, MaterialDesignIconic.Icon.gmi_apps);
        setIconDrawable(mUpdate, MaterialDesignIconic.Icon.gmi_download);
        setIconDrawable(mAbout, MaterialDesignIconic.Icon.gmi_account);
        setIconDrawable(mTheme, MaterialDesignIconic.Icon.gmi_palette);
        setIconDrawable(mJiaocheng, MaterialDesignIconic.Icon.gmi_book);
        Picasso.with(MainActivity.this)
                .load(R.mipmap.kn)
                .placeholder(new IconicsDrawable(this)
                        .icon(FoundationIcons.Icon.fou_photo)
                        .color(Color.GRAY)
                        .backgroundColor(Color.WHITE)
                        .roundedCornersDp(40)
                        .paddingDp(15)
                        .sizeDp(75))
                .transform(new CropCircleTransformation())
                .into(mAvatar);

        if (PreferencesUtils.getBoolean(this, "isFirst", true)) {
            mResideLayout.openPane();
            PreferencesUtils.putBoolean(this, "isFirst", false);
        }
        mIcon.setImageDrawable(new IconicsDrawable(this).color(Color.WHITE).icon(MaterialDesignIconic.Icon.gmi_android).sizeDp(20));
        mTitle.setText(AppValue.BARTITLE);
        switchFragment("Android");
        checkVersion();
    }
//检查更新
    private void checkVersion() {
        Observable.create(new ObservableOnSubscribe<AVObject>() {
            @Override
            public void subscribe(final ObservableEmitter<AVObject> emitter) throws Exception {
                AVQuery<AVObject> avQuery = new AVQuery<>(NetValue.VERSION);
                avQuery.getInBackground(NetValue.VERSION_OBJECTID, new GetCallback<AVObject>() {
                    @Override
                    public void done(final AVObject avObject, AVException e) {
                        if(e==null){
                            int netversionCode = avObject.getInt("versionCode");
                            if(netversionCode>appVersionCode){
                                updateFlag=true;
                                emitter.onNext(avObject);
                            }else {
                                updateFlag=false;
                                emitter.onComplete();
                            }
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AVObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(final AVObject avObject) {
                                new MaterialDialog.Builder(MainActivity.this)
                                        .title("提示")
                                        .icon(new IconicsDrawable(MainActivity.this)
                                                .color(ThemeUtils.getThemeColor(MainActivity.this, R.attr.colorPrimary))
                                                .icon(MaterialDesignIconic.Icon.gmi_info)
                                                .sizeDp(20))
                                        .content("发现新版本是否更新？")
                                        .positiveText(R.string.close)
                                        .negativeText("确定")
                                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                                            @Override
                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                final MaterialDialog downloaddialog = new MaterialDialog.Builder(MainActivity.this)
                                                        .customView(R.layout.view_download, false)
                                                        .show();
                                                View customeView = downloaddialog.getCustomView();
                                                TextView textView = (TextView) customeView.findViewById(R.id.downloadingtitle);
                                                textView.setText("下载更新");
                                                textView.setTextColor(ThemeUtils.getThemeColor(MainActivity.this, R.attr.colorPrimary));
                                                textView.setCompoundDrawablesWithIntrinsicBounds(new IconicsDrawable(MainActivity.this)
                                                                .icon(MaterialDesignIconic.Icon.gmi_download)
                                                                .color(ThemeUtils.getThemeColor(MainActivity.this, R.attr.colorPrimary))
                                                                .sizeDp(16),
                                                        null, null, null);
                                                textView.setCompoundDrawablePadding(DimenUtils.dp2px(MainActivity.this, 10));
                                                final NumberProgressBar gaDownloadingView = (NumberProgressBar) customeView.findViewById(R.id.downloadpb);
                                                final File file = new File(Environment.getExternalStorageDirectory(), "Mlibrary/MLibrary.apk");
                                                FileDownloader.getImpl().create(avObject.getString("apkUrl")).setPath(file.getPath()).setListener(new FileDownloadListener() {
                                                    @Override
                                                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                                    }

                                                    @Override
                                                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                                                        int percent = (int) ((double) soFarBytes / (double) totalBytes * 100);
                                                        gaDownloadingView.setProgress(percent);
                                                    }

                                                    @Override
                                                    protected void blockComplete(BaseDownloadTask task) {

                                                    }

                                                    @Override
                                                    protected void completed(BaseDownloadTask task) {
                                                        downloaddialog.dismiss();
                                                        install(file);
                                                    }

                                                    @Override
                                                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                                    }

                                                    @Override
                                                    protected void error(BaseDownloadTask task, Throwable e) {
                                                    }

                                                    @Override
                                                    protected void warn(BaseDownloadTask task) {
                                                        while (task.getSmallFileSoFarBytes() != task.getSmallFileTotalBytes()) {
                                                            int percent = (int) ((double) task.getSmallFileSoFarBytes() / (double) task.getSmallFileTotalBytes() * 100);
                                                            gaDownloadingView.setProgress(percent);
                                                        }
                                                    }
                                                }).start();
                                            }
                                        })
                                        .show();
                    }
                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if(isShouDongUpdate){
                            if(!updateFlag){
                                isShouDongUpdate=false;
                                new MaterialDialog.Builder(MainActivity.this)
                                        .title("提示")
                                        .icon(new IconicsDrawable(MainActivity.this)
                                                .color(ThemeUtils.getThemeColor(MainActivity.this, R.attr.colorPrimary))
                                                .icon(MaterialDesignIconic.Icon.gmi_download)
                                                .sizeDp(20))
                                        .content("暂无更新")
                                        .positiveText(R.string.close)
                                        .show();
                            }
                        }
                    }
                });





    }
    private void install(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this
                    , "com.yyydjk.library.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }
    //    检查权限
    private void chechPremission() {
        Observable.just(1).subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        List<PermissionItem> permissonItems = new ArrayList<>();
                        permissonItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "存储", R.drawable.permission_ic_storage));
                        permissonItems.add(new PermissionItem(Manifest.permission.READ_PHONE_STATE, "手机状态", R.drawable.permission_ic_phone));
                        HiPermission.create(MainActivity.this)
                                .permissions(permissonItems)
                                .checkMutiPermission(new PermissionCallback() {
                                    @Override
                                    public void onClose() {

                                    }

                                    @Override
                                    public void onFinish() {

                                    }

                                    @Override
                                    public void onDeny(String permission, int position) {

                                    }

                                    @Override
                                    public void onGuarantee(String permission, int position) {

                                    }
                                });
                    }
                });

    }

    protected void setIconDrawable(TextView view, IIcon icon) {
        view.setCompoundDrawablesWithIntrinsicBounds(new IconicsDrawable(this)
                        .icon(icon)
                        .color(Color.WHITE)
                        .sizeDp(16),
                null, null, null);
        view.setCompoundDrawablePadding(DimenUtils.dp2px(this, 10));
    }


    public void switchFragment(String name) {
        if (currentFragmentTag != null && currentFragmentTag.equals(name))
            return;
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        Fragment currentFragment = fragmentManager.findFragmentByTag(currentFragmentTag);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        Fragment foundFragment = fragmentManager.findFragmentByTag(name);

        if (foundFragment == null) {
            if (name.equals("Android")){
                foundFragment = new AndroidLibraryFragment();
            }else if(name.equals("JiaoCheng")){
                foundFragment = new JiaoChengFragment();
            }
        }

        if (foundFragment == null) {

        } else if (foundFragment.isAdded()) {
            ft.show(foundFragment);
        } else {
            ft.add(R.id.container, foundFragment, name);
        }
        ft.commit();
        currentFragmentTag = name;
    }


    @Override
    public void onBackPressed() {
        if (mResideLayout.isOpen()) {
            mResideLayout.closePane();
        } else {
            super.onBackPressed();
        }
    }

    @OnClick({R.id.avatar, R.id.android, R.id.front,
            R.id.about, R.id.theme, R.id.icon,R.id.app,R.id.update,R.id.jiaocheng})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.avatar:
                break;
            case R.id.android:
                mResideLayout.closePane();
                mIcon.setImageDrawable(new IconicsDrawable(this).color(Color.WHITE).icon(MaterialDesignIconic.Icon.gmi_android).sizeDp(20));
                mTitle.setText("Android");
                switchFragment("Android");
                break;
            case R.id.front:
//                mResideLayout.closePane();
//                mIcon.setImageDrawable(new IconicsDrawable(this).color(Color.WHITE).icon(MaterialDesignIconic.Icon.gmi_language_javascript).sizeDp(20));
//                AppValue.BARTITLE="前端";
//                mTitle.setText(AppValue.BARTITLE);
                Toasty.info(getApplicationContext(), "正在筹备中...", Toast.LENGTH_SHORT, true).show();
                break;
            case R.id.app:
//                mResideLayout.closePane();
//                mIcon.setImageDrawable(new IconicsDrawable(this).color(Color.WHITE).icon(MaterialDesignIconic.Icon.gmi_apps).sizeDp(20));
//                AppValue.BARTITLE="App";
//                mTitle.setText(AppValue.BARTITLE);
                Toasty.info(getApplicationContext(), "正在筹备中...", Toast.LENGTH_SHORT, true).show();
                break;
            case R.id.jiaocheng:
                mResideLayout.closePane();
                mIcon.setImageDrawable(new IconicsDrawable(this).color(Color.WHITE).icon(MaterialDesignIconic.Icon.gmi_book).sizeDp(20));
                mTitle.setText("教程");
                switchFragment("JiaoCheng");
                break;
            case R.id.update:
                isShouDongUpdate=true;
                checkVersion();
                break;
            case R.id.about:
                new MaterialDialog.Builder(this)
                        .title(R.string.about)
                        .icon(new IconicsDrawable(this)
                                .color(ThemeUtils.getThemeColor(this, R.attr.colorPrimary))
                                .icon(MaterialDesignIconic.Icon.gmi_account)
                                .sizeDp(20))
                        .content(R.string.about_me)
                        .positiveText(R.string.close)
                        .show();
                break;
            case R.id.theme:
                new ColorChooserDialog.Builder(this, R.string.theme)
                        .customColors(R.array.colors, null)
                        .doneButton(R.string.done)
                        .cancelButton(R.string.cancel)
                        .allowUserColorInput(false)
                        .allowUserColorInputAlpha(false)
                        .show();
                break;
            case R.id.icon:
                mResideLayout.openPane();
                break;
        }
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, @ColorInt int selectedColor) {
        if (selectedColor == ThemeUtils.getThemeColor(this, R.attr.colorPrimary))
            return;
        EventBus.getDefault().post(new SkinChangeEvent());

        if (selectedColor == getResources().getColor(R.color.colorBluePrimary)) {
            setTheme(R.style.BlueTheme);
            PreUtils.setCurrentTheme(this, Theme.Blue);

        } else if (selectedColor == getResources().getColor(R.color.colorRedPrimary)) {
            setTheme(R.style.RedTheme);
            PreUtils.setCurrentTheme(this, Theme.Red);

        } else if (selectedColor == getResources().getColor(R.color.colorBrownPrimary)) {
            setTheme(R.style.BrownTheme);
            PreUtils.setCurrentTheme(this, Theme.Brown);

        } else if (selectedColor == getResources().getColor(R.color.colorGreenPrimary)) {
            setTheme(R.style.GreenTheme);
            PreUtils.setCurrentTheme(this, Theme.Green);

        } else if (selectedColor == getResources().getColor(R.color.colorPurplePrimary)) {
            setTheme(R.style.PurpleTheme);
            PreUtils.setCurrentTheme(this, Theme.Purple);

        } else if (selectedColor == getResources().getColor(R.color.colorTealPrimary)) {
            setTheme(R.style.TealTheme);
            PreUtils.setCurrentTheme(this, Theme.Teal);

        } else if (selectedColor == getResources().getColor(R.color.colorPinkPrimary)) {
            setTheme(R.style.PinkTheme);
            PreUtils.setCurrentTheme(this, Theme.Pink);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepPurplePrimary)) {
            setTheme(R.style.DeepPurpleTheme);
            PreUtils.setCurrentTheme(this, Theme.DeepPurple);

        } else if (selectedColor == getResources().getColor(R.color.colorOrangePrimary)) {
            setTheme(R.style.OrangeTheme);
            PreUtils.setCurrentTheme(this, Theme.Orange);

        } else if (selectedColor == getResources().getColor(R.color.colorIndigoPrimary)) {
            setTheme(R.style.IndigoTheme);
            PreUtils.setCurrentTheme(this, Theme.Indigo);

        } else if (selectedColor == getResources().getColor(R.color.colorLightGreenPrimary)) {
            setTheme(R.style.LightGreenTheme);
            PreUtils.setCurrentTheme(this, Theme.LightGreen);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepOrangePrimary)) {
            setTheme(R.style.DeepOrangeTheme);
            PreUtils.setCurrentTheme(this, Theme.DeepOrange);

        } else if (selectedColor == getResources().getColor(R.color.colorLimePrimary)) {
            setTheme(R.style.LimeTheme);
            PreUtils.setCurrentTheme(this, Theme.Lime);

        } else if (selectedColor == getResources().getColor(R.color.colorBlueGreyPrimary)) {
            setTheme(R.style.BlueGreyTheme);
            PreUtils.setCurrentTheme(this, Theme.BlueGrey);

        } else if (selectedColor == getResources().getColor(R.color.colorCyanPrimary)) {
            setTheme(R.style.CyanTheme);
            PreUtils.setCurrentTheme(this, Theme.Cyan);

        }
        final View rootView = getWindow().getDecorView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache(true);

        final Bitmap localBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
        rootView.setDrawingCacheEnabled(false);
        if (null != localBitmap && rootView instanceof ViewGroup) {
            final View tmpView = new View(getApplicationContext());
            tmpView.setBackgroundDrawable(new BitmapDrawable(getResources(), localBitmap));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) rootView).addView(tmpView, params);
            tmpView.animate().alpha(0).setDuration(400).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    ColorUiUtil.changeTheme(rootView, getTheme());
                    System.gc();
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    ((ViewGroup) rootView).removeView(tmpView);
                    localBitmap.recycle();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();
        }
    }
}
